package com.atguigu.juc;

import java.util.concurrent.*;

public class MyThreadPoolDemo {

    public static void main(String[] args) {
        MyselfExecutor();
    }

    public static void MyselfExecutor() {
        System.out.println(Runtime.getRuntime().availableProcessors());
        ExecutorService threadPool = new ThreadPoolExecutor(
                40,
                80,
                10L, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        try {
            //模拟有10个顾客到银行办理业务，目前池子里有5个工作人员提供服务
            for (int i = 1; i <= 20; i++) {
                threadPool.execute(() -> {
                    try {  TimeUnit.SECONDS.sleep(1L);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t 办理业务");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }


    public static void initPool() {
        //        ExecutorService threadPool = Executors.newFixedThreadPool(5);  //一个池子5个线程
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();   //一池子一线程
        ExecutorService threadPool = Executors.newCachedThreadPool();   //一池N个线程，可自动扩容
        try {
            //模拟有10个顾客到银行办理业务，目前池子里有5个工作人员提供服务
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t 办理业务");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

}
